package com.golden.zip.module;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.nutz.dao.Dao;
import org.nutz.dao.Sqls;
import org.nutz.dao.sql.Sql;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.mvc.annotation.AdaptBy;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Fail;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.Param;
import org.nutz.mvc.upload.TempFile;
import org.nutz.mvc.upload.UploadAdaptor;

import com.golden.zip.bean.CssFile;
import com.golden.zip.filter.XFilter;
import com.golden.zip.query.ZipQuery;
import com.golden.zip.util.ZipUtils;

@IocBean
@At("/cssFile")
@Ok("json")
@Fail("http:500")
public class CssFileModule {

    @Inject
    protected Dao dao;
    
    // 上传文件存储目录
    private static final String UPLOAD_DIRECTORY = "zip"+File.separator+"cssUpload";
    
    @At
    @Ok("jsp:pages/cssList")
    public void cssList(){
    }
    
    /**
     * 查询树列表第一级
     * @return
     */
    @At
    public List<ZipQuery> queryFirst() {
        Sql sql = Sqls.create("select t.id,t.name,t.servername,t.mod_flag as modFlag,t.parent_id as parentId,t.order_id as orderId,(SELECT COUNT(0) FROM T_ZIP_CSSFILE C WHERE C.PARENT_ID = t.id) as childCount,CASE (SELECT COUNT(0) FROM T_ZIP_CSSFILE C WHERE C.PARENT_ID = t.id) WHEN 0 THEN 'open'  ELSE 'closed' END AS state  from T_ZIP_CSSFILE t  where t.parent_id=-1 order by t.order_id");
        sql.setCallback(Sqls.callback.entities());
        sql.setEntity(dao.getEntity(ZipQuery.class));
        dao.execute(sql);
        List<ZipQuery> list = sql.getList(ZipQuery.class);
        return list; 
    }
    
    /**
     * 查询树列表下一级
     * @param parentId
     * @return
     */
    @At
    public List<ZipQuery> queryNext(@Param("parentId")String parentId){
        Sql sql = Sqls.create("select t.id,t.name,t.servername,t.mod_flag as modFlag,t.parent_id as parentId,t.order_id as orderId,to_char(t.opertime,'yyyy-MM-dd') as operTime,(SELECT COUNT(0) FROM T_ZIP_CSSFILE C WHERE C.PARENT_ID = t.id) as childCount,CASE (SELECT COUNT(0) FROM T_ZIP_CSSFILE C WHERE C.PARENT_ID = t.id) WHEN 0 THEN 'open'  ELSE 'closed' END AS state,t.remark,t.filename  from T_ZIP_CSSFILE t  where t.parent_id=@parentId order by t.order_id");
        sql.params().set("parentId", parentId);
        sql.setCallback(Sqls.callback.entities());
        sql.setEntity(dao.getEntity(ZipQuery.class));
        dao.execute(sql);
        List<ZipQuery> list = sql.getList(ZipQuery.class);
        return list;
    }
    
    /**
     * 新增文件夹
     * @param param
     * @return
     */
    @At
    @AdaptBy(type = UploadAdaptor.class, args = { "${app.root}/WEB-INF/tmp" })
    public Integer insertCssFolder(@Param("..")HashMap<String,Object> param){
        CssFile cssFile=new CssFile();
        cssFile.setName(String.valueOf(param.get("name")));
        cssFile.setModFlag(0);
        cssFile.setOrderId(String.valueOf(param.get("orderId")));
        cssFile.setParentId(String.valueOf(param.get("parentId")));
        Date nowTime=new Date(); 
        cssFile.setOperTime(nowTime); 
        CssFile result=dao.insert(cssFile);
        if(result!=null){
            return 1;
        }else{
            return 0;
        }
    }
    
    @At
    @Ok("jsp:pages/webuploader")
    public void upload(){
    }
    
    /**
     * 新增文件
     * @param param
     * @return
     */
    @At
    @AdaptBy(type = UploadAdaptor.class, args = { "${app.root}/WEB-INF/tmp" })
    public Integer insertCssFile(@Param("..")HashMap<String,Object> param,@Param("file") TempFile tf){
        // 这个路径相对当前应用的目录
        HttpServletRequest request=XFilter.requests.get();
        String uploadPath = request.getSession().getServletContext().getRealPath("./") + File.separator + UPLOAD_DIRECTORY;
        Integer result=0;
        try {
            //上传的文件保存在临时目录，先把临时目录中的zip或rar文件放在uolpad文件夹里
            tf.write(uploadPath+File.separator+tf.getSubmittedFileName());
            //删除临时文件
            tf.delete();
            CssFile cssFile=new CssFile();
            cssFile.setName(String.valueOf(param.get("name")));
            cssFile.setModFlag(1);
            cssFile.setOrderId(String.valueOf(param.get("orderId")));
            cssFile.setParentId(String.valueOf(param.get("parentId")));
            cssFile.setRemark(String.valueOf(param.get("remark")));
            cssFile.setServerName(File.separator+tf.getSubmittedFileName());
            Date nowTime=new Date(); 
            cssFile.setOperTime(nowTime); 
            CssFile resutlCss=dao.insert(cssFile);
            if(resutlCss!=null){
                result= 1;
            }else{
                result= 0;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }
    
    /**
     * 修改文件夹名称
     * @param param
     * @return
     */
    @At
    @AdaptBy(type = UploadAdaptor.class, args = { "${app.root}/WEB-INF/tmp" })
    public Integer updateCssFolder(@Param("..")HashMap<String,Object> param){
        CssFile cssFile=new CssFile();
        cssFile.setId(String.valueOf(param.get("id")));
        cssFile.setName(String.valueOf(param.get("name")));
        cssFile.setOrderId(String.valueOf(param.get("orderId")));
        Integer result=dao.updateIgnoreNull(cssFile);
        if(result!=null){
            return 1;
        }else{
            return 0;
        }
    }
    
    /**
     * 修改文件名称或备注
     * @param param
     * @return
     */
    @At
    @AdaptBy(type = UploadAdaptor.class, args = { "${app.root}/WEB-INF/tmp" })
    public Integer updateCssFile(@Param("..")HashMap<String,Object> param){
        CssFile cssFile=new CssFile();
        cssFile.setId(String.valueOf(param.get("id")));
        cssFile.setName(String.valueOf(param.get("name")));
        cssFile.setOrderId(String.valueOf(param.get("orderId")));
        cssFile.setRemark(String.valueOf(param.get("remark")));
        Integer result=dao.updateIgnoreNull(cssFile);
        if(result!=null){
            return 1;
        }else{
            return 0;
        }
    }
    
    /**
     * 删除文件
     * @param param
     * @return
     */
    @At
    public Integer deleteCssFile(@Param("id")String id){
        CssFile cssFile=new CssFile();
        cssFile.setId(id);
        CssFile resultCssFile = dao.fetch(CssFile.class,id);
        Integer result=0;
        HttpServletRequest request=XFilter.requests.get();
        String uploadPath = request.getSession().getServletContext().getRealPath("./") + File.separator + UPLOAD_DIRECTORY;
        //删除上传的压缩包
        boolean deleteZip=ZipUtils.deleteFile(uploadPath+File.separator+resultCssFile.getServerName());
        if(deleteZip){
            result=dao.delete(cssFile);
        }
        return result;
    }
}
